package rpc

import (
	"context"
	"encoding/json"
	proto "gykjgit.dccnet.com.cn/chain/proto/swarm"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"time"
)

type ContainerServer struct {
}

func (c *ContainerServer) Logs(ctx context.Context, in *proto.ReqContainerLogs) (*proto.RespContainerLogs, error) {
	data, err := client.Obtain().Container().Logs(ctx, in.ContainerID, time.Unix(in.Since.Sec, in.Since.Nsec), time.Unix(in.Until.Sec, in.Until.Nsec))
	if nil != err {
		return &proto.RespContainerLogs{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespContainerLogs{Code: proto.Code_success, Logs: data}, nil
}

func (c *ContainerServer) List(ctx context.Context, _ *proto.ReqContainerList) (*proto.RespContainerList, error) {
	cs, err := client.Obtain().Container().List(ctx)
	if nil != err {
		return &proto.RespContainerList{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	data, err := json.Marshal(cs)
	if nil != err {
		return &proto.RespContainerList{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespContainerList{Code: proto.Code_success, Containers: data}, nil
}

func (c *ContainerServer) Inspect(ctx context.Context, in *proto.ReqContainerInspect) (*proto.RespContainerInspect, error) {
	cJson, data, err := client.Obtain().Container().Inspect(ctx, in.ContainerID)
	if nil != err {
		return &proto.RespContainerInspect{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	containerBytes, err := json.Marshal(cJson)
	if nil != err {
		return &proto.RespContainerInspect{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespContainerInspect{Code: proto.Code_success, Container: containerBytes, Data: data}, nil
}

func (c *ContainerServer) Stats(ctx context.Context, in *proto.ReqContainerStats) (*proto.RespContainerStats, error) {
	stat, osType, err := client.Obtain().Container().Stats(ctx, in.ContainerID)
	if nil != err {
		return &proto.RespContainerStats{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	data, err := json.Marshal(stat)
	if nil != err {
		return &proto.RespContainerStats{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespContainerStats{Code: proto.Code_success, Stats: data, OsType: osType}, nil
}

func (c *ContainerServer) StatsAll(ctx context.Context, _ *proto.ReqContainerStatsAll) (*proto.RespContainerStatsAll, error) {
	stats, err := client.Obtain().Container().StatsAll(ctx)
	if nil != err {
		return &proto.RespContainerStatsAll{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	data, err := json.Marshal(stats)
	if nil != err {
		return &proto.RespContainerStatsAll{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespContainerStatsAll{Code: proto.Code_success, Stats: data}, nil
}
